﻿using System.Net.WebSockets;

namespace WebApi.Controllers
{
    public class WebSocketConnectionManager
    {
        private Dictionary<string, WebSocket> connections = new Dictionary<string, WebSocket>();
        private int onlineUserCount = 0;

        //检测到链接时加入列表
        public void AddWebSocket(WebSocket webSocket)
        {
            string connectionId = Guid.NewGuid().ToString();
            connections.TryAdd(connectionId, webSocket);
        }

        //断开链接时移除列表中数据
        public void RemoveWebSocket(WebSocket webSocket)
        {
            var connection = connections.FirstOrDefault(pair => pair.Value == webSocket);
            if (!connection.Equals(default(KeyValuePair<string, WebSocket>)))
            {
                connections.Remove(connection.Key);
            }
        }

        //获取当前连接数
        public int GetOnlineUserCount()
        {
            return onlineUserCount;
        }

        //链接计数器
        public void IncrementOnlineUserCount()
        {
            onlineUserCount++;
        }
        public void DecrementOnlineUserCount()
        {
            if (onlineUserCount > 0)
            {
                onlineUserCount--;
            }
        }
    }
}
